package com.bestcem.xm.common.core.sql.calculator;

import com.bestcem.xm.common.core.sql.ConditionConstant;
import com.bestcem.xm.common.core.sql.ConditionException;
import com.bestcem.xm.common.core.sql.ConditionProxy;
import com.bestcem.xm.common.core.sql.ParamsProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 示例服务
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2022/3/24
 */
@Slf4j
public class IncludeConditionCalculator extends ConditionCalculator {

    private Map<String, List<String>> groupMap;

    public IncludeConditionCalculator(ConditionProxy conditionProxy, ParamsProxy paramsProxy) {
        super(conditionProxy, paramsProxy);
    }

    public void setGroupMap(Map<String, List<String>> groupMap) {
        this.groupMap = groupMap;
    }

    /**
     * 获取支持的数据类型
     */
    @Override
    protected List<String> getSupportedDataTypes() {
        return Arrays.asList(ConditionConstant.FieldTypes.LEVEL);
    }

    /**
     * 获取操作符
     */
    @Override
    protected String getOperator() {
        return ConditionConstant.Operators.INCLUDE;
    }

    /**
     * 具体计算逻辑
     */
    @Override
    protected boolean onCalculate() {
        String dataType = this.conditionProxy.getDataType();
        // 目前只有层级才有这个选项
        if (StringUtils.equals(dataType, ConditionConstant.FieldTypes.LEVEL)) {
            return this.onLevelCalculate();
        } else {
            return false;
        }
    }

    private boolean onLevelCalculate() {
        List<Object> values = this.conditionProxy.listValues();
        if (CollectionUtils.isEmpty(values) || values.size() < 1) {
            throw new ConditionException(String.format("condition.value %s illegal", values));
        }

        Object endValue = values.get(values.size() - 1);
        if (endValue == null) {
            String msg = String.format("condition.value missing for level, endValue: %s", endValue);
            throw new ConditionException(msg);
        }

        // 参数校验
        Object paramValue = this.getParamValue();
        if (ObjectUtils.isEmpty(paramValue)) {
            return this.getDefaultResult();
        }
        List<String> groups = groupMap.get(paramValue);

        return groups.contains(paramValue);
    }
}
